import { Api } from "../../../utils/api.js"
import { Http } from '../../../utils/http.js'
import { TimeToDate } from '../../../utils/timeToDate.js'
const http = new Http()
const timeToDate = new TimeToDate()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsCoupons: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getGoodsCoupons()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 自定义方法
   */


  /**
   * 获取优惠券列表
   *  */
  getGoodsCoupons: function (isPullToRefresh) {
    var that = this
    http.sendHttp(Api.get_all_coupons, {
      data: { },
      success: function (res) {
        var coupons = res.data.obj.coupons
        for (var index in coupons) {
          coupons[index].tmEnd = timeToDate.formatTime(coupons[index].tmEnd / 1000, 'Y-M-D')
        }
        var mCoupons = []
        if (!isPullToRefresh) {
          mCoupons = that.data.goodsCoupons
        }
        mCoupons = coupons
        that.setData({
          goodsCoupons: mCoupons,
        })
        that.setGoodsCoupons()
      }

    })

  },

  setGoodsCoupons: function () {
    var amount = this.data.amount
    var goodsCoupons = []
    this.data.goodsCoupons.forEach((item, index) => {
        goodsCoupons.push(item)
    })
    this.setData({
      goodsCoupons: goodsCoupons
    })
  },


  /**
   * 点击优惠券
   **/
  selectCoupon: function(e) {
    //领取接口
    var couponId = e.detail.couponId
    var that = this
    http.sendHttp(Api.receive_coupon, {
      data: {
        couponId: couponId
      },
      success: function (res) {
        wx.showToast({
          title: '领取成功',
          icon: 'none'
        })
      },
      finish: function () {
        that.getGoodsCoupons()
      }
    }, 'POST')
  }
})